<template>
  <el-container style="height: 100vh; border: 1px solid #eee">
    <el-aside width="200px" style="background-color: rgb(238, 241, 246)">
      <el-menu :default-openeds="['1','2', '3']" router>
        <el-submenu index="1">
          <template slot="title"><i class="el-icon-message"></i>终端配置</template>
          <el-menu-item-group>
            <template slot="title"></template>
            <el-menu-item index="/map">终端地图</el-menu-item>
            <el-menu-item index="/home">摄像头配置</el-menu-item>
          </el-menu-item-group>
          <el-menu-item index="delcam">删除终端</el-menu-item>
        </el-submenu>
        <el-submenu index="2">
          <template slot="title"><i class="el-icon-menu"></i>数据管理</template>
          <el-menu-item index="list">摄像头数据</el-menu-item>
          <!-- <el-menu-item index="/statistic_chart">统计图表</el-menu-item> -->
        </el-submenu>
        <el-submenu index="3">
          <template slot="title"><i class="el-icon-setting"></i>视频查看</template>
          <el-menu-item-group>
            <template slot="title"></template>
            <el-menu-item index="liveview">实时浏览</el-menu-item>
            <el-menu-item index="review">录像视频</el-menu-item>
            <el-menu-item index="live">多路播放</el-menu-item>
          </el-menu-item-group>
        </el-submenu>
      </el-menu>
    </el-aside>

    <el-container>
      <el-header style="text-align: right; font-size: 12px">
        <el-dropdown>
          <i class="el-icon-setting" style="margin-right: 15px"></i>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item @click.native="safe_quit">安全退出</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <span>{{person_name}}</span>
      </el-header>
      <el-main>
        <video class="myvideo" id="video" muted controls autoplay preload="auto"></video>
        <el-tabs type="border-card" id="eltable" tab-position="right" @tab-click="tabclick" v-model="terminal_id">
          <el-tab-pane v-for="(item,index) in terminal_id_dev" :key="index" :label="item.label" :name="item.name">
            <!-- 播放{{terminal_id_dev[index].devId}} -->
            <div class="control">
              <!-- 刷新 开关 -->
              <el-button icon="el-icon-refresh" type="primary"></el-button>
              <el-button icon="el-icon-switch-button" type="primary" :disabled="switchplay" @click="close"></el-button>
              <!-- 日历 -->
              <div class="block">
                <!-- <span class="demonstration">带快捷选项</span> -->
                <el-date-picker v-model="value1" align="right" type="date" placeholder="选择日期" value-format="yyyy-MM-dd"
                  :picker-options="pickerOptions" @change="seldata">
                </el-date-picker>
              </div>
              <el-table :data="tablelist" height="200">
                <el-table-column prop="starttime" label="开始时间" width="180">
                </el-table-column>
                <el-table-column prop="endtime" label="结束时间" width="120">
                </el-table-column>
                <el-table-column prop="operate" label="操作">
                  <template slot-scope="scope">
                    <el-button @click="replay(scope.row)" type="text" size="small">查看</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-main>
      <el-footer style="text-align: center; font-size: 10px">
        版权所有 © 雷佳千
      </el-footer>
    </el-container>
  </el-container>
</template>

<script>
  import {
    getPTZCmd
  } from '../../static/ptz.js'
  import {
    Webrtc
  } from '../../static/webrtc.js'

  export default {
    name: "liveview",
    editableTabsValue: "2",
    data() {
      return {
        switchplay: true,
        webrtc: "",
        value: false,
        person_name: '',
        active: 0,
        terminal: "", //当前点击的tab的所有信息
        terminal_id: '', //当前配置的id//当前点击的tab的所有信息
        terminal_id_dev: [], //数据库中终端信息存储、、多个终端的数据
        pickerOptions: { //日历数据
          disabledDate(time) {
            return time.getTime() > Date.now();
          },
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          }, {
            text: '昨天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', date);
            }
          }, {
            text: '一周前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', date);
            }
          }]
        },
        value1: '',
        value2: '',
        tableData: [],
        replaylist: [], //从后台无序地拉取到的数据。只是一个终端的数据
        tablelist: []
      }
    },
    methods: {
      tabclick() { //初始化terminal
        console.log("--tab--")
        this.terminal = {
          "devId": this.terminal_id_dev[this.terminal_id].devId,
          "channel": this.terminal_id_dev[this.terminal_id].channel,
          "channelNo": this.terminal_id_dev[this.terminal_id].channelNo
        }
        console.log(this.terminal)
      },
      change(index) {

      },
      close() { //关闭当前德播放
        this.webrtc.stop("测试");
      },
      seldata() { //选择日期@
        var now = this.value1;
        //starttime
        this.value1 = this.value1 + "T16:00:00";
        // endtime
        this.value2 = (now + 'T15:59:59').toString();

        let source = new EventSource(
          // "http://219.138.126.226:18298/api/gb28181/list"
          "http://localhost:15391/gb28181/list"
        )
        const _this = this
        source.addEventListener('message', function (e) {
          console.log("rdata");
          const data = JSON.parse(e.data);
          // console.log(e);
          _this.replaylist = data;
          if (_this.replaylist == null) {
            console.log("no invite")
          } else {
            console.log("invite")
            _this.$options.methods.getlist(_this)
          }
          source.close();
        });
      },

      getlist(that) { //list，摄像头的list在replaylist,list包含了转换好的数据
        console.log("=getlist=")

        for (var i = 0, l = that.replaylist.length; i < l; i++) {
          // console.log(that.replaylist[i].ID)
          if (that.replaylist[i].ID === that.terminal.devId) {
            console.log("=getlistdata=")
            // console.log(that.replaylist[i].Channels.Records)
            let list = that.replaylist[i].Channels[0].Records
            // console.log(list)
            for (var j = 0, l = list.length; j < l; j++) {
              var one = {
                starttime: list[j].StartTime,
                endtime: list[j].EndTime, //.slice(11, 19)
                channelNo: list[j].DeviceID,
                devId: that.terminal.devId, // 只有一个录像机，先把写死
                time: Date.parse(list[j].StartTime.replace("T", " ")).toString().substring(0, 10)
              }
              console.log(one)
              that.tablelist.push(one)
            }
          }
        }

      },

      replay(index) { //播放录像
        console.log("replay")
        console.log(index)
        this.switchplay = false;
        var videoip = "localhost:15391";
        this.webrtc = new Webrtc(videoip);
        var devId = index.devId;
        var channelNo = index.channelNo;
        var channel = 0;
        var starttimeStamp = Date.parse(index.starttime.replace("T", " ")).toString().substring(0, 10);
        var endtimeStamp = Date.parse(index.endtime.replace("T", " ")).toString().substring(0, 10);
        var time = index.time; //时间戳
        this.webrtc.addrePlayStream("video", "测试", "", devId, channel, channelNo, starttimeStamp, endtimeStamp, time);
        this.webrtc.invitereplay("测试").then((d) => {
          if (d == 200 || d == 304) {
            this.webrtc.play("测试");
          }
        })
      },

      stop(that) {
        console.log("stop");
        let cmd = getPTZCmd({
          type: "stop"
        });
        let url = that.$options.methods.getCmdUrl("测试", cmd, that);
        that.get(url).then(d => {
          console.log(d);
        });
      },

      getCmdUrl(name, cmd, that) {
        return "http://219.138.126.226:18298/gb28181/control?id=" + that.webrtc.streams["测试"].devId + "&channel=" +
          that
          .webrtc
          .streams["测试"].channel + "&ptzcmd=" + cmd;
      },

      // get请求url
      get(url) {
        return new Promise((resolve, reject) => {
          let xhr = new XMLHttpRequest();
          xhr.open("GET", url);
          xhr.onload = () => {
            resolve(xhr.status);
          }
          xhr.onerror = () => {
            reject(xhr.status);
          }
          xhr.send();
        }).catch(e => {
          console.log(e);
        })
      }
    },
    beforeCreate() {
      let arr = []
      this.$http.get(this.$site + 'api/see_config')
        .then((response) => {
          response = response.body;
          for (var i = 0; i < response.length; i++) {
            var demo = {
              "label": "终端" + response[i].terminal,
              "devId": response[i].devId,
              "channelNo": response[i].channelNo,
              "channel": response[i].channel
            };
            this.terminal_id_dev.push(demo)
          }
        });

    },

    mounted() {
      console.log("replayview渲染完");
      var person_name = sessionStorage.getItem('person_name');
      if (person_name === null) {
        this.$router.push('/')
      } else {
        this.person_name = person_name
      };
      this.editableTabsValue = this.terminal_id_dev.length

      setTimeout(() => {
        this.terminal = { //当前点击的tab的所有信息
          "devId": this.terminal_id_dev[0].devId,
          "channelNo": this.terminal_id_dev[0].channelNo,
          "change": this.terminal_id_dev[0].channel
        }
      }, 1000)
    }
  }

</script>

<style scoped>
  .is-selected {
    color: #1989FA;
  }

  .block {
    margin-top: 40px;
  }

  .el-header {
    background-color: #B3C0D1;
    color: #333;
    line-height: 60px;
  }

  .el-aside {
    color: #333;
  }

  #eltable {
    height: 380px;
  }

  video {
    width: 683px;
    height: 384px;
    float: left;
    background-color: rgb(207, 57, 57);
  }

  .control {
    float: right;
    width: 420px;
    height: 300px;
  }

  .change_camera_direction {
    background-color: rgb(255, 255, 255);
    text-align: center;
    /* position: absolute; */
    top: 0%;
    width: 160px;
    height: 160px;
    float: right;
    /* margin-right: 120px; */
    margin-top: 120px;
  }

  .change_camera_direction .camera_title {
    color: rgb(39, 145, 206);
    font-size: 15px;
    margin: 5% auto;
  }

  .direction_content {
    width: 100%;
    height: 70%;
    position: relative;
  }

  .direction_div {
    position: relative;
    width: 30px;
    height: 30px;
  }

  .direction_div img {
    width: 100%;
    height: 100%;
  }

  /*left*/
  .left_direction {
    top: 5%;
    left: 20%;
  }

  /*bottom*/
  .bottom_direction {
    top: 5%;
    left: 40%;
  }

  /*right*/
  .right_direction {
    top: -49%;
    left: 61%;
  }

  /*top*/
  .top_direction {
    top: 2%;
    left: 40%;
  }

  /* el-switch */
  .el-main {
    padding-top: 40px;
    padding-right: 0;
    padding-left: 0;
  }

</style>
